const BACKEND = "http://localhost:8082"
const PARAMS = new URLSearchParams(window.location.search);

function fetchAndRenderSection() {
	const apiUrl = `${BACKEND}/section/${PARAMS.get("section")}`;  
	const section = document.getElementById('section');
	fetch(apiUrl, {
		credentials: "include"
		})
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch classes');  
	        }  
	        return response.json();  
	    })  
	    .then(data => {  
			section.textContent = `${data.section.semester} ${data.course.name} ${data.section.id}`;  
	    })  
	    .catch(error => {  
	        console.error('Error fetching classes:', error);  
	    });  
}

function fetchStudents(order) {  
    return fetch(`${BACKEND}/section/${PARAMS.get('section')}/student?order=${order}`, {
		credentials: "include"
	})
        .then(response => {  
            if (!response.ok) {  
                throw new Error('Failed to fetch students');  
            }  
            return response.json();
        })  
        .then(data => {  
            return data;  
        })  
        .catch(error => {  
            console.error('Error fetching students:', error);  
            return [];  
        });  
}  
  
// 渲染学生列表  
function renderStudentList(students) {  
    const studentBody = document.getElementById('student-body');  
    studentBody.innerHTML = '';
  
    students.forEach(student => {  
        const row = document.createElement('tr');  
        row.innerHTML = `  
			<td>${student.student.id}</td>  
			<td>${student.student.name}</td>  
			<td>${student.student.sex}</td>  
			<td><input type="number" value="${student.score.usual}" onchange="submit(event)"></td>  
			<td><input type="number" value="${student.score.midterm}" onchange="submit(event)"></td>  
			<td><input type="number" value="${student.score.experiment}" onchange="submit(event)"></td>  
			<td><input type="number" value="${student.score.terminal}" onchange="submit(event)"></td>  
			<td><input type="number" value="${student.score.total}" readonly></td>
		`;  
        studentBody.appendChild(row);  
    });  
}  
  
// 获取学生数据并渲染到页面上  
function fetchAndRender(order) {
	fetchAndRenderSection();
	fetchStudents(order)
	    .then(students => {  
	        renderStudentList(students);  
	    })  
	    .catch(error => {  
	        console.error('Error fetching students:', error);  
	    });
}

fetchAndRender("id");

// 更新成绩
function submit(event) {
	event.preventDefault();
    const input = event.target;
    const row = input.closest('tr');
	const studentId = row.querySelector('td:nth-child(1)').textContent;
	const cells = row.querySelectorAll('td input');
	const usual = Number(cells[0].value);
	const midterm = Number(cells[1].value);  
	const experiment = Number(cells[2].value);  
	const terminal = Number(cells[3].value);  
	const total = usual + midterm + experiment + terminal;  
	cells[4].value = total;
	const scores = {  
	    'usual': usual,  
	    'midterm': midterm,  
	    'experiment': experiment,  
	    'terminal': terminal,  
	    'total': total  
	};  
	// 发送更新到服务器  
	fetch(`${BACKEND}/section/${PARAMS.get('section')}/student/${studentId}/score`, {  
		method: 'POST',  
		credentials: "include",
		headers: {  
			'Content-Type': 'application/json'  ,
		},  
		body: JSON.stringify(scores)  
	})  
	.then(response => {  
		if (!response.ok) {  
			throw new Error('Failed to update students');  
			showMessage("更新失败"); 
		}  
		showMessage("更新成功"); 
	})  
	.catch(error => {  
		console.error('Error updating students:', error);  
		showMessage("更新失败"); 
	});  
}

// 显示消息
function showMessage(text, duration = 3000) { // duration in milliseconds  
    const messageContainer = document.getElementById('messageContainer');  
    const message = document.createElement('div');  
    message.className = 'message';  
    message.textContent = text;  
    messageContainer.appendChild(message);  
  
    // 设置定时器在指定时间后移除消息框  
    setTimeout(() => {  
        message.classList.add('fadeOut'); // 可以添加一个额外的类来触发CSS动画  
        setTimeout(() => {  
            messageContainer.removeChild(message);  
        }, duration);  
    }, duration);  
}  

// 基于准备好的dom，初始化echarts实例  
const myChart = echarts.init(document.getElementById('main'));  
fetch(`${BACKEND}/section/${PARAMS.get('section')}/distribution`, {
	credentials: "include"
})
	.then(response => {  
		if (!response.ok) {  
			throw new Error('Failed to fetch students');  
		}  
		return response.json();
	})  
	.then(data => {  
		// 指定图表的配置项和数据
		const option = {  
			title: {  
				text: '学生成绩分布' 
			},  
			tooltip: {
				
			},  
			xAxis: {  
				data: ['[0,60)', '[60,70)', '[70,80)', '[80,90)', '[90,100]']  
			},  
			yAxis: {},  
			series: [{  
				name: '人数',  
				type: 'bar',  
				data: [data._0_60, data._60_70, data._70_80, data._80_90, data._90_100_]
			}]  
		};  
		// 使用刚指定的配置项和数据显示图表。  
		myChart.setOption(option);
		
	})  
	.catch(error => {  
		console.error('Error fetching students:', error);  
		return [];  
	});  
